<template>
	<view class="register-container">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<template v-slot:content>注册</template>
		</cu-custom>

		<view class="padding-xl">
			<view class="text-center margin-bottom-xl">
				<text class="text-xxl text-bold text-shadow">加入我们</text>
			</view>

			<form>
                <view class="cu-form-group">
					<view class="title">用户名</view>
					<input placeholder="请输入用户名" v-model="username" type="text" />
				</view>
				<view class="cu-form-group">
					<view class="title">手机号</view>
					<input placeholder="请输入手机号" v-model="phone" type="number" />
				</view>
				<view class="cu-form-group">
					<view class="title">密码</view>
					<input placeholder="请输入密码" v-model="password" type="password" />
				</view>
                <view class="cu-form-group">
					<view class="title">确认密码</view>
					<input placeholder="请再次输入密码" v-model="confirmPassword" type="password" />
				</view>
				<view class="cu-form-group">
					<view class="title">验证码</view>
					<input placeholder="请输入验证码" v-model="captcha" type="text" />
					<view class="cu-capsule radius" @click="refreshCaptcha">
						<image :src="captchaUrl" mode="aspectFit" style="width: 120rpx; height: 50rpx" v-if="captchaUrl" />
						<view class="cu-tag bg-white" v-else>加载中</view>
					</view>
				</view>

				<view class="padding-xl">
					<button class="cu-btn block bg-gradual-blue lg" @click="handleRegister" :loading="loading">
						{{ loading ? '注册中...' : '立即注册' }}
					</button>
				</view>
			</form>

			<view class="flex justify-center padding-lr-xl">
				<navigator url="/pages/login/login" class="text-blue">已有账号？立即登录</navigator>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { post, get } from '@/utils/request.js';

const username = ref('');
const phone = ref('');
const password = ref('');
const confirmPassword = ref('');
const captcha = ref('');
const captchaUrl = ref('');
const captchaKey = ref('');
const loading = ref(false);

const getCaptcha = async () => {
  try {
    const response = await get('/captcha/code', {
      responseType: 'arraybuffer' ,
      headers: { 'Accept': 'application/json' }
    });
    const base64 = uni.arrayBufferToBase64(response.data);
    captchaUrl.value = `data:image/png;base64,${base64}`;
    const key = response.header['x-captcha-key'] || response.header['key'];
    if (key) {
      captchaKey.value = key;
    } else {
      console.error('响应头中未找到 X-Captcha-Key');
    }
  } catch (err) {
    console.error('获取验证码失败:', err);
    uni.showToast({ title: '验证码获取失败', icon: 'none' });
  }
};

const refreshCaptcha = () => {
  getCaptcha();
};

const handleRegister = async () => {
  if (!username.value.trim() || !phone.value.trim() || !password.value.trim() || !confirmPassword.value.trim() || !captcha.value.trim()) {
    return uni.showToast({ title: '请填写所有字段', icon: 'none' });
  }
  if (password.value !== confirmPassword.value) {
    return uni.showToast({ title: '两次输入的密码不一致', icon: 'none' });
  }
  if (!captchaKey.value) {
    return uni.showToast({ title: '请先获取验证码', icon: 'none' });
  }

  loading.value = true;
  try {
    const res = await post('/login/register', {
      username: username.value,
      account: phone.value,
      phone: phone.value,
      password: password.value,
      inputCaptcha: captcha.value,
      key: captchaKey.value
    });

    if (res.data.code !== 200) {
      uni.showToast({ title: res.data.msg || '注册失败', icon: 'none' });
      refreshCaptcha();
      return;
    }

    uni.showToast({ title: '注册成功！', icon: 'success' });
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/login/login' });
    }, 1500);

  } catch (err) {
    console.error('注册错误:', err);
    uni.showToast({
      title: err.message || '注册失败，请重试',
      icon: 'none'
    });
    refreshCaptcha();
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getCaptcha();
});
</script>

<style scoped>
.register-container {
	background-color: #f8f8f8;
	min-height: 100vh;
}
</style> 